package com.qk;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtText {
    /**
     * 生成jwt
     */
    @Test
    public void generateJwt(){
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",100);
        claims.put("username","admin");
        claims.put("age",20);

        String jwt = Jwts.builder()
                .setClaims(claims) //添加自定义的数据信息
                .signWith(SignatureAlgorithm.HS256, "cWluZ2tl") //签名算法，密钥
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 30)) //设置过期时间 30秒
                .compact();
        System.out.println(jwt);
    }

    /**
     * 解析jwt
     *  1. 令牌被篡改 , 解析时直接报错 ;
     *  2. 令牌过期, 解析时直接报错 ;
     */
    @Test
    public void parseJwt(){
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MTAwLCJleHAiOjE3NTM5NDQ1NzksImFnZSI6MjAsInVzZXJuYW1lIjoiYWRtaW4ifQ.LlfzkrzvTLY413LVLzCoaHl3Elt_eK9WdVytUkeh19s";
        Claims claims = Jwts.parser()
                .setSigningKey("cWluZ2tl")
                .parseClaimsJws(jwt)
                .getBody();
        System.out.println(claims);
    }
}
